/*
 * @Descripttion: 
 * @version: V1.0.0
 * @Author: LeonHe
 * @Date: 2021-10-17 02:25:01
 * @LastEditTime: 2021-10-30 23:42:05
 */

#include "params.h"
#include "string.h"

stSettParamDef gStSettParam = {0};
stDataParamDef gStDataParam = {0};

void eepWrite(uint16_t Adr, uint8_t *pData, uint16_t Len);
void eepRead(uint16_t Adr, uint8_t *pData, uint16_t Len);

void paramsInit(void)
{
    eepRead(PARAMS_EEP_ADDR_SETT, (uint8_t *)&gStSettParam, sizeof(gStSettParam));
    if(gStSettParam.valueValid != PARAMS_VALUE_VALID)
    {
        memset(&gStSettParam, 0, sizeof(gStSettParam));
        gStSettParam.valueValid = PARAMS_VALUE_VALID;
    }
    
    eepRead(PARAMS_EEP_ADDR_DATA, (uint8_t *)&gStDataParam, sizeof(gStDataParam));
    if(gStDataParam.valueValid != PARAMS_VALUE_VALID)
    {
        memset(&gStDataParam, 0, sizeof(gStDataParam));
        gStSettParam.channelEnable[0] = 1;
        gStSettParam.channelEnable[1] = 1;
        gStDataParam.valueValid = PARAMS_VALUE_VALID;
    }

    if(!gStSettParam.channelEnable[0] && !gStSettParam.channelEnable[1])
    {
        gStSettParam.channelEnable[0] = 1;
        gStSettParam.channelEnable[1] = 1;
    }
}

void paramsWrite(void)
{
   eepWrite(PARAMS_EEP_ADDR_SETT, (uint8_t *)&gStSettParam, sizeof(gStSettParam));
}

void paramsDataWrite(void)
{
   eepWrite(PARAMS_EEP_ADDR_DATA, (uint8_t *)&gStDataParam, sizeof(gStDataParam));
}

//写EEPROM
void eepWrite(uint16_t Adr, uint8_t *pData, uint16_t Len)
{
		@far uint8_t *p;
		//p指针指向EEPROM 对应的单元
        if(Adr%4)
        {
            //4字节对齐
            Adr &= 0xFFFC;
            Adr += 4;
        }
		p = (uint8_t*)0x4000 + Adr;   
		//解锁
        /*Define FLASH programming time*/
        FLASH_SetProgrammingTime(FLASH_PROGRAMTIME_STANDARD);
        /* Unlock Data memory */
        FLASH_Unlock(FLASH_MEMTYPE_DATA);
		//写数据
		for( ; Len > 4; Len-=4)
		{
            // FLASH_ProgramWord((uint32_t)p, *((uint32_t*)pData));
            // p+=4;
            // pData+=4;

            FLASH->CR2 |= FLASH_CR2_WPRG;
            FLASH->NCR2 &= (uint8_t)(~FLASH_NCR2_NWPRG);
            *p++ = *pData++;
            *p++ = *pData++;
            *p++ = *pData++;
            *p++ = *pData++;

		} 
		for( ; Len > 0; Len--)
		{
            *p++ = *pData++;
		} 
		//加锁
        FLASH_Lock(FLASH_MEMTYPE_DATA);
}

//读EEPROM
void eepRead(uint16_t Adr, uint8_t *pData, uint16_t Len)
{
		uint8_t *p;
		//p指针指向EEPROM 对应的单元
		p = (uint8_t*)0x4000 + Adr; 

		//解锁
        // FLASH_Unlock(FLASH_MEMTYPE_DATA);

		//读数据
		for( ; Len > 0; Len--)
			*pData++ = *p++;

		//加锁EEPROM
        // FLASH_Lock(FLASH_MEMTYPE_DATA);
}
